/**
 * pro-form-render -- 组件面板
 * @author SPY
 * @url 语雀:https://www.yuque.com/study365
 */

import React, { useEffect, memo } from 'react';
import { useDrop, useDrag } from 'ahooks';
import { connect } from 'umi';
import _ from 'lodash';
import { Collapse, Tooltip } from 'antd';
import { basicList, dateList, advancedList } from './formItemList';
import styles from './index.less';

const { Panel } = Collapse;

const FormItemPanel = ({ dispatch }) => {
  const getDragProps = useDrag();
  const [props, { isHovering }] = useDrop({
    onDom: (content, e) => {
      const uniqueId = _.uniqueId(content);
      const itemProps = {
        key: _.uniqueId('pro_form_key'), // 生成唯一id
        type: content, // 组件的类型
        name: uniqueId,
        label: uniqueId, // name和label默认生成，后面可以更改
      };
      // 添加组件表单
      if (dispatch) {
        dispatch({
          type: 'proForm/addFormItem',
          payload: {
            formItem: itemProps,
          },
        });
      }
    },
  });

  useEffect(() => {
    // 生成拖动区域范围
    if (dispatch) {
      dispatch({
        type: 'proForm/save',
        payload: {
          dragProps: props,
        },
      });
    }
  }, []);

  return (
    <Collapse
      defaultActiveKey={['1']}
      ghost
      accordion
      className={styles.collapse}
    >
      <Panel header="基础组件" key="1">
        {basicList.map((item, i) => (
          <Tooltip title={item.title} placement="right" key={i}>
            <div {...getDragProps(`${item.type}`)} className={styles.leftItem}>
              {item.type}
            </div>
          </Tooltip>
        ))}
      </Panel>
      <Panel header="日期组件" key="2">
        {dateList.map((item, i) => (
          <Tooltip title={item.title} placement="right" key={i}>
            <div {...getDragProps(`${item.type}`)} className={styles.leftItem}>
              {item.type}
            </div>
          </Tooltip>
        ))}
      </Panel>
      <Panel header="高级组件" key="3">
        {advancedList.map((item, i) => (
          <Tooltip title={item.title} placement="right" key={i}>
            <div {...getDragProps(`${item.type}`)} className={styles.leftItem}>
              {item.type}
            </div>
          </Tooltip>
        ))}
      </Panel>
    </Collapse>
  );
};

export default connect(({ proForm }) => ({
  ...proForm,
}))(memo(FormItemPanel));
